package com.zerdoor.service.impl;

import com.zerdoor.dao.IArtistPersonalHomeDao;
import com.zerdoor.pagehelper.Page;
import com.zerdoor.pagehelper.PageHelper;
import com.zerdoor.pagehelper.PageInfo;
import com.zerdoor.service.IArtistPersonalHomeService;
import com.zerdoor.service.ICommonPayService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by zhongjieyu on 2014/11/14.
 * 艺术家个人主页 业务层实现类（包括主页、作品专辑、作品集）
 */
@Service
public class ArtistPersonalHomeServiceImpl implements IArtistPersonalHomeService {

    @Autowired
    private IArtistPersonalHomeDao artistPersonalHomeDao;

    @Autowired
    private ICommonPayService commonPayService;

    @Override
    public Map<String, Object> findArtistPersonalHome(int receiver) throws Exception {


//        int receiver = Integer.parseInt(param.get("receiver"));
        //最终返回Map
        Map<String,Object> dataMap = new HashMap<String, Object>();
        //转换数据集list
        List list = new ArrayList();
        //艺术家基本信息
        Map<String,Object> artist = artistPersonalHomeDao.findArtistBasicDataByUserId(receiver);

        //加入服务范围
        artist.put("service",artistPersonalHomeDao.findTaskTypeByIds(artist.get("service") + ""));
        //成交金额和笔数
        artist.put("successTotalPrice",artistPersonalHomeDao.findSuccessTotalPriceByReceiver(receiver));
        //进行中的金额和笔数
        artist.put("inTotalPrice",artistPersonalHomeDao.findInTotalPriceByReceiver(receiver));
        //评价百分比数据
        artist.put("appraise",artistPersonalHomeDao.findAppraiseByAppraiser(receiver));

        dataMap.put("artist",artist);

        //设置已完成作品案例 分页查询
        PageHelper.startPage(1, 6);
        list.addAll(artistPersonalHomeDao.findFinishProductionByReceiver(receiver));
        dataMap.put("finishProduction", list);


        //设置出售中作品 分页查询
        PageHelper.startPage(1, 6);
        list = new ArrayList();
        list.addAll(artistPersonalHomeDao.findSalesProductionByReceiver(receiver));
        dataMap.put("salesProduction", list);

        //设置艺术家评价 分页查询
        PageHelper.startPage(1, 6);
        Map<String,String> params = new HashMap<String, String>();

        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date dd = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dd);
        calendar.add(Calendar.DATE,-30);
        String startTime = format.format(calendar.getTime() ) ;
        //String endTime = format.format(dd ) ;

        params.put("receiver",receiver + "");
        params.put("startTime",startTime);
        //params.put("endTime",endTime);

        list = new ArrayList();
        list.addAll(artistPersonalHomeDao.findAppraiseInfoByReceiver(params));
        dataMap.put("appraiseInfo", list);


        //设置评价统计
        dataMap.put("countAppraise",artistPersonalHomeDao.findCountAppraiseByReceiver(params));
        //设置进行中的项目
        dataMap.put("inTaskInfo",artistPersonalHomeDao.findInTaskInfoByReceiver(receiver));

        return dataMap;
    }

    @Override
    public List<Map<String, String>> findFinishProductionByReceiver(int receiver) throws Exception {


        return artistPersonalHomeDao.findFinishProductionByReceiver(receiver);
    }

    @Override
    public List<Map<String, String>> findSalesProductionByReceiver(int receiver) throws Exception {

        return artistPersonalHomeDao.findSalesProductionByReceiver(receiver);
    }

    @Override
    public List<Map<String, String>> findAppraiseInfoByReceiver(Map<String, String> param) throws Exception {

//        Map<String,Object> dataMap = new HashMap<String, Object>();

//        dataMap.put("appraiseInfo",artistPersonalHomeDao.findAppraiseInfoByReceiver(param));
//        dataMap.put("countAppraise",artistPersonalHomeDao.findCountAppraiseByReceiver(param));

//        return dataMap;
        return artistPersonalHomeDao.findAppraiseInfoByReceiver(param);
    }


    @Override
    public List<Map<String, Object>> findUserPhotoByUserId(int userId) throws Exception {

        //查出作品相册
        List<Map<String, Object>> list = artistPersonalHomeDao.findUserPhotoByUserId(userId);


        for(Map<String, Object> map : list){
            int photoId = Integer.parseInt(map.get("photo_id").toString());

            //根据作品相册ID得到作品ID和作品封面
            map.put("works",artistPersonalHomeDao.findUserWorksByPhotoId(photoId));
        }

        return list;
    }

    @Override
    public List<Map<String, String>> selectAllUserProductionByPhotoId(Map<String,String> param) throws Exception {

        return artistPersonalHomeDao.selectAllUserProductionByPhotoId(param);
    }

    @Override
    public Map<String, Object> updatefindUserProductionByProductionId(int productionId,int userID) throws Exception {

        Map<String, Object> data = artistPersonalHomeDao.findUserProductionByProductionId(productionId);

        if(data != null){

            Map<String, Integer> param = new HashMap<String, Integer>();
            param.put("works_id",productionId);
            param.put("user_id",userID);

            String orderId = artistPersonalHomeDao.findOrderWorksByUserId(param);

            //等于0 表示订单表中不存在，那么就把作品包路径清空
            if(orderId == null || "".equals(orderId)){

                //清空作品包路径
                data.put("works_url","");
            }

            //把订单ID放入结果集
            data.put("orderId",orderId );


            if(userID != 0){
                //放入钱包余额
                data.put("wallet",commonPayService.findUserWalletEnough(userID) );
            }


            //放入导航
            Map navigation = artistPersonalHomeDao.findNavigationByWorksId(productionId);
            data.put("navigation",navigation);


            //放入ACG合同条例
            String ACGProvision = artistPersonalHomeDao.findACGProvision();
            data.put("ACGProvision",ACGProvision);


            //增加点击量
            artistPersonalHomeDao.updateClickRateById(productionId);
        }

        return data;
    }



    @Override
    public boolean updateBuyWorkByPaypay(String works_id, int userID) throws Exception {


        return false;
    }

    @Override
    public boolean updateBuyWorkByAlipay(String works_id, int userID) throws Exception {
        return false;
    }

    @Override
    public boolean updateBuyWorkByBalance(String works_id, int userID) throws Exception {

        //返回数据Map 暂时不使用
        Map<String,Object> dataMap = new HashMap<String, Object>();

        String priceStr = artistPersonalHomeDao.findWorksPriceByWorksId(works_id);

        //如果为空表示该作品状态不为可出售，不能购买
        if(priceStr == null || "".equals(priceStr)){

            dataMap.put("static","0");
            dataMap.put("msg","该作品为不可出售，不能购买！");

            return false;
        }
        //得到应付金额
        float sumPrice = Float.parseFloat(priceStr);

        //根据作品得到艺术家信息
        Map<String,String> artistId = artistPersonalHomeDao.findArtistIdByWorksId(works_id);

        //如果为空表示传入的作品ID存在
        if(artistId == null){

            dataMap.put("static","0");
            dataMap.put("msg","传入的作品ID不正确！");

            return false;
        }

        //支付 类型：112109 表示购买作品
        boolean payFlag = commonPayService.updateDeductUserWalletByUserId(sumPrice,userID,112109);

        //如果支付标识为false 那么就表示没有支付成功
        if(!payFlag){

            dataMap.put("static","0");
            dataMap.put("msg","支付失败，余额不足或账户被冻结！");

            return false;
        }

        //查询手续费比例  参数1为配置项固定ID
        float workFee = commonPayService.findScaleValue( 1 );

        //艺术家应得金额，扣除手续费后的
        float artistMoney = sumPrice - (sumPrice * workFee /100) ;

        int artist_user_id = Integer.parseInt(String.valueOf(artistId.get("user_id")));
        //收入，类型：112105表示作品收入
        commonPayService.updateChargeUserWalletByUserId(artistMoney,artist_user_id,112105);

        //作品订单参数
        Map<String,String> orderWork = new HashMap<String, String>();
        orderWork.put("works_id",works_id);
        orderWork.put("price",priceStr);
        orderWork.put("fee", sumPrice - artistMoney + "");
        orderWork.put("artist_id",artistId.get("artist_id"));

        String baile_id = artistPersonalHomeDao.findUserBaileByUserId(userID);
        orderWork.put("baile_id",baile_id);

        //插入作品订单表信息
        artistPersonalHomeDao.addOrderWorks(orderWork);

        //更新作品信息
        artistPersonalHomeDao.updateWorksSaleNumByWorksId(works_id);

        //维护用户双方交易量
        commonPayService.updateUserTradingNumByUserId(artist_user_id);
        commonPayService.updateUserTradingNumByUserId(userID);

        dataMap.put("static","1");
        dataMap.put("msg","购买成功！");

        return true;
    }

    @Override
    public Map findNavigationByArtistId(int artistId) throws Exception {


        return artistPersonalHomeDao.findNavigationByArtistId(artistId);
    }

    @Override
    public Map findNavigationByPhotoId(int photoId) throws Exception {

        return artistPersonalHomeDao.findNavigationByPhotoId(photoId);
    }


}
